package com.yl.users.common.handler

import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import org.slf4j.LoggerFactory
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.validation.BindException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import org.springframework.web.servlet.NoHandlerFoundException
import javax.validation.ConstraintViolationException


@RestControllerAdvice
class DefaultExceptionHandler {
	companion object {
		private val log = LoggerFactory.getLogger(DefaultExceptionHandler::class.java)
	}

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException::class)
	fun handleException(e: HttpRequestMethodNotSupportedException): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.INCORRECT_REQUEST_MODE, "请求方式不支持")
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception::class)
	fun handleException(e: Exception): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.SERVER_ERROR, "服务器异常，请联系管理员")
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(NoHandlerFoundException::class)
	fun handleException(e: NoHandlerFoundException): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.NO_HANDLER_FOUND, "访问路径错误")
	}

	/**
	 * 参数转换错误
	 */
	@ExceptionHandler(HttpMessageNotReadableException::class)
	fun httpMessageNotReadableException(e: HttpMessageNotReadableException): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.PARAM_EMPTY)
	}

	/**
	 * 参数不能为空
	 */
	@ExceptionHandler(ConstraintViolationException::class)
	fun constraintViolationException(e: ConstraintViolationException): ResponseBody {
		log.error(e.message, e)
		e.message ?: return returnError(ErrorCode.PARAM_EMPTY)
		return returnError(ErrorCode.PARAM_EMPTY, e.message!!)
	}

	/**
	 * 参数类型错误
	 */
	@ExceptionHandler(MethodArgumentTypeMismatchException::class)
	fun methodArgumentTypeMismatchException(e: MethodArgumentTypeMismatchException): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.PARAMETER_FORMAT_ERROR, "参数格式错误")
	}

	/**
	 * 参数不能为空
	 */
	@ExceptionHandler(BindException::class)
	fun bindException(e: BindException): ResponseBody {
		log.error(e.message, e)
		return returnError(ErrorCode.PARAM_EMPTY, "请输入完整的数据")
	}


}
